package day11.reflect2;

import java.lang.reflect.Field;

import org.junit.Before;
import org.junit.Test;

public class Demo5 {
	Class<?> class1 ;
	
	//每次运行@Test方法前会先执行有@Before的方法
	@Before
	public void before() {
		class1 = Student.class;
	}
	
	//获取所有public 修改的字段
	@Test
	public void test() {
		Field[] fields = class1.getFields();
		System.out.println("fields.length:" + fields.length);
		
		for (Field field : fields) {
			System.out.println(field);
		}
	}
	
	//获取Student类的所有字段，包括private/public/protected/default
	@Test
	public void test2() {
		Field[] fields = class1.getDeclaredFields();
		System.out.println("fields.length:" + fields.length);
		
		for (Field field : fields) {
			System.out.println(field);
		}
	}
	
	//获取指定的字段 name是private 
	@Test
	public void test3() throws NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException {
		Field field = class1.getDeclaredField("name");
		
		//暴力反射
		field.setAccessible(true);
		
		//创建对象
		Object obj = class1.newInstance();
		
		field.set(obj, "admin");
		
		System.out.println(obj);
	}
	
	@Test
	public void test4() throws NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException {
		Field field = class1.getDeclaredField("sex");
		
		//创建对象
		Object obj = class1.newInstance();
		
		// stu.sex="男"
		field.set(obj, "男");
		
		System.out.println(obj);
	}
	
	
}
